#include <hpdf.h>
#include <cstdlib>
#include <cstdio>
#include <cassert>

#ifdef _WIN32
#include <windows.h>
#endif

void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void *user_data)
{
    HPDF_UNUSED(user_data);
    fprintf(stderr, "ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no, (HPDF_UINT)detail_no);
}

int main()
{
    HPDF_Doc pdf = HPDF_New(error_handler, NULL);
    if (!pdf)
    {
        fprintf(stderr, "Cannot create PDF object.\n");
        return 1;
    }

    // Enable the use of Chinese fonts
    HPDF_UseCNSFonts(pdf);
    HPDF_SetCompressionMode(pdf, HPDF_COMP_ALL);
    HPDF_UseUTFEncodings(pdf);
    HPDF_SetCurrentEncoder(pdf, "UTF-8");

    // Use Kaiti font
    const char *font_name = HPDF_LoadTTFontFromFile(pdf, "./kaiti.ttf", HPDF_TRUE);
    assert(font_name);
    // auto font = HPDF_GetTTFontDefFromFile(pdf, "./kaiti.ttf", HPDF_TRUE);
    HPDF_Font font = HPDF_GetFont(pdf, font_name, "UTF-8");
    assert(font != nullptr);

    // Define the number of characters per page and per line
    int charsPerLine = 15;
    int linesPerPage = 20; // Adjust this value based on your page size and font size

    HPDF_Page page = HPDF_AddPage(pdf);
    HPDF_Page_SetFontAndSize(page, font, 12);

    HPDF_REAL y = 750; // Start from the top of the page
    HPDF_Page_BeginText(page);

    // Unicode range for Chinese characters (simplified and traditional)
    // This range is a simplified example and may not cover all characters
    int start_code = 0x4E00; // Start of CJK Unified Ideographs
    int end_code = 0x9FA5;   // End of CJK Unified Ideographs (simplified Chinese)

    for (int code = start_code; code <= end_code; ++code)
    {
        HPDF_BYTE text[2] = {0};
        text[0] = (HPDF_BYTE)((code >> 8) & 0xFF);
        text[1] = (HPDF_BYTE)(code & 0xFF);

        // Calculate x position based on the length of the text
        HPDF_REAL x = (HPDF_Page_GetWidth(page) - HPDF_Page_TextWidth(page, (const char *)text)) / 2; // Center the text

        // Output the text
        HPDF_Page_TextOut(page, x, y, (const char *)text);

        // Move to the next line
        y -= 20; // Adjust the line spacing based on your font size

        // If we've reached the bottom of the page, start a new page
        if (y < 50)
        {
            HPDF_Page_EndText(page);
            page = HPDF_AddPage(pdf);
            HPDF_Page_SetFontAndSize(page, font, 12);
            y = 750; // Reset y position for the new page
            HPDF_Page_BeginText(page);
        }
    }

    HPDF_Page_EndText(page);

    // Save the document to a file
    HPDF_SaveToFile(pdf, "chinese_characters.pdf");

    // Clean up
    HPDF_Free(pdf);

    return 0;
}